'use strict';

const _ = require('lodash');

exports.index = async ctx => {
  const { query } = ctx.request;
  let pageSize = 10;
  if (query.pageSize) pageSize = Number(query.pageSize);
  const where = {};
  const { type } = query;
  if (type) where.type = type;
  const options = {
    limit: pageSize,
    offset: query.currentPage ? pageSize * (query.currentPage - 1) : 0,
    raw: true,
    where,
  };
  const {
    count: total, rows: list,
  } = await ctx.model.File.findAndCountAll(options);
  ctx.body = {
    list,
    pagination: {
      total,
      pageSize,
      current: parseInt(query.currentPage, 10) || 1,
    },
  };
};

exports.create = async ctx => {
  ctx.validate({
    hash: { type: 'string' },
    type: { type: 'enum', values: [ 'image', 'video' ] },
  });
  const currentUser = await ctx.model.User.findByPk(ctx.state.user.sub);
  const { role } = currentUser;
  if (role === 'admin') {
    ctx.body = await ctx.model.File.create(_.pick(
      ctx.request.body,
      [ 'hash', 'type' ]
    ));
  }
};

exports.show = async ctx => {
  const options = { raw: true };
  const file = await ctx.model.File.findByPk(ctx.params.id, options);
  if (file) {
    ctx.body = file;
  } else {
    ctx.status = 404;
  }
};

exports.update = async ctx => {
  const file = await ctx.model.File.findByPk(ctx.params.id);
  const currentUser = await ctx.model.User.findByPk(ctx.state.user.sub);
  const { role } = currentUser;
  if (file && role === 'admin') {
    ctx.validate({
      hash: { type: 'string', required: false },
      type: { type: 'enum', values: [ 'image', 'video' ], required: false },
    });
    ctx.body = await file.update(_.pickBy(
      _.pick(
        ctx.request.body,
        [ 'hash', 'type' ]
      ),
      value => value !== null
    ));
  } else {
    ctx.status = 404;
  }
};

exports.destroy = async ctx => {
  const file = await ctx.model.File.findByPk(ctx.params.id);
  const currentUser = await ctx.model.User.findByPk(ctx.state.user.sub);
  const { role } = currentUser;
  if (file && role === 'admin') {
    await file.destroy();
    ctx.status = 204;
  } else {
    ctx.status = 404;
  }
};
